package com.xjuse.yida.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjuse.yida.commom.ConstantEnum;
import com.xjuse.yida.commom.gaode.GaodeIpServiceUtil;
import com.xjuse.yida.commom.jwt.JwtUser;
import com.xjuse.yida.commom.jwt.PasswordEncoder;
import com.xjuse.yida.commom.jwt.TokenProvider;
import com.xjuse.yida.commom.jwt.interceptor.AuthStorage;
import com.xjuse.yida.commom.util.NetworkUtils;
import com.xjuse.yida.commom.util.Result;
import com.xjuse.yida.entity.UserClothes;
import com.xjuse.yida.entity.UserInfo;
import com.xjuse.yida.mapper.UserInfoMapper;
import com.xjuse.yida.service.LocationWeatherService;
import com.xjuse.yida.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjuse.yida.service.WearRecommandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author duwx
 * @since 2022-10-22
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private LocationWeatherService locationWeatherService;
    @Autowired
    private WearRecommandService wearRecommandService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertUser(UserInfo userInfo) {
        //初始化为用户有效
        userInfo.setIsValid(true)
                .setRegisterTime(LocalDateTime.now());
        int result = userInfoMapper.insert(userInfo);
        return result>0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(UserInfo userInfo) {
        int result = userInfoMapper.updateById(userInfo);
        return result>0;
    }

    @Override
    public List<UserInfo> queryUserList() {
        return userInfoMapper.selectList(new QueryWrapper<>());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(String userId) {
        int result = userInfoMapper.deleteById(userId);
        return result>0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserLogical(String userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo!=null){
            //置为无效
            userInfo.setIsValid(false);
            userInfoMapper.updateById(userInfo);
        }
        return false;
    }

    /***
     * @Description  用户信息注册  roleId  1:管理员注册  2：普通用户注册
     * @return com.xjuse.yida.entity.UserInfo
     * @author 嗜雪的蚂蚁
     **/
    @Transactional(rollbackFor = Exception.class)
    public Result register(String username,String password, String sex,int roleId) {
        UserInfo userByName = userInfoMapper.getUserByName(username);
        if (userByName!=null&& !StringUtils.isEmpty(userByName.getUserId())){
            return Result.failed("用户名信息已存在!");
        }
        UserInfo userInfo = UserInfo.builder()
                .userName(username)
                .userPwd(PasswordEncoder.md5Encode(password))
                .sex((boolean) ConstantEnum.getEnumByStr(sex).getData())
                .roleId(roleId).build();
        boolean result = this.insertUser(userInfo);
        if (result){
            return Result.ok("注册成功");
        }else {
            return Result.failed("服务器错误，注册失败，请重试!");
        }
    }

    /***
     * 用户登录后的后续处理
     * 1.记录用户的登录信息
     * 2.记录用户的定位信息和天气信息，用以进行衣物穿搭推荐
     * @author 嗜雪的蚂蚁
     **/
    @Override
    @Async
    public void handlerAfterLogin(String token, HttpServletRequest request) {
        JwtUser jwtUser = TokenProvider.checkToken(token);
        if (jwtUser==null||StringUtils.isEmpty(jwtUser.getUserId())){
            return;
        }
        String userId = jwtUser.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfo userWithLoginTime = UserInfo.builder().userId(userInfo.getUserId()).lastLoginTime(LocalDateTime.now()).build();
        //以本次登录时间 作为 “lastLoginTime” 记录
        userInfoMapper.updateById(userWithLoginTime);
        //todo 这里获取IP地址有问题
//        String userIp = NetworkUtils.getIpAddr(request);
//        String userIp = "42.93.157.251";
        String userIp = "42.95.157.251";
        //用户定位及天气信息查询更新
        boolean locationRes = locationWeatherService.insertLocation(userInfo, userIp);
        boolean weatherRes = locationWeatherService.insertWeather(userInfo);
        //生成用户衣物清洁提醒数据
        List<UserClothes> userClothes = wearRecommandService.needCleanUserClothesList(userId);
    }
}
